package cn.virens.config;

import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FrameworkServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

/**
 * Spring MVC 启动器（代替web.xml）
 * 
 * @文件   :SpringSartupInitializer.java
 * @作者   :cn.loioi
 * @创建时间 :2016年10月13日 下午1:12:26
 */
public class SpringStartupInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	@Override
	protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
		DispatcherServlet dispatcherServlet = new DispatcherServlet(servletAppContext);
		dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

		return dispatcherServlet;
	}

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		super.onStartup(servletContext);

		registerDruidStatViewServlet(servletContext);
	}

	@Override
	protected Filter[] getServletFilters() {
		return new Filter[] { //
				new WebStatFilter(), //
				new CharacterEncodingFilter("UTF-8"), //
				new DelegatingFilterProxy("springSessionRepositoryFilter"), //
				new DelegatingFilterProxy("shiroFilter") };
	}

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[] { ServletRootConfig.class };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[] { ServletWebConfig.class };
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/*" };
	}

	/**
	 * 配置druid的SQL监控servlet
	 * 
	 * @param servletContext
	 */
	private void registerDruidStatViewServlet(ServletContext servletContext) {
		ServletRegistration.Dynamic druidStatViewServlet = servletContext.addServlet("druidStatView", new StatViewServlet());
		druidStatViewServlet.setInitParameter("loginUsername", "druid");
		druidStatViewServlet.setInitParameter("loginPassword", "druid");
		druidStatViewServlet.setInitParameter("resetEnable", "true");
		druidStatViewServlet.addMapping("/druid/*");
		druidStatViewServlet.setLoadOnStartup(1);
	}
}